package org.dromara.sheet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.sheet.domain.*;
import org.dromara.sheet.domain.bo.SysSheetButtonAuthBo;
import org.dromara.sheet.domain.dto.SheetFormAuthDataDto;
import org.dromara.sheet.domain.dto.platformList.SearchDataSourceDto;
import org.dromara.sheet.domain.vo.*;
import org.dromara.sheet.enums.HandleStateEnum;
import org.dromara.sheet.enums.YesOrNoEnum;
import org.dromara.sheet.mapper.*;
import org.dromara.sheet.service.SysSheetAuthService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用授权接口实现
 *
 * @author yangshanlin
 * @date 2023/12/7 15:49
 * @describe
 */
@RequiredArgsConstructor
@Service
public class SysSheetAuthServiceImpl implements SysSheetAuthService {

    private final SysSheetButtonAuthMapper sheetButtonAuthMapper;
    private final SysSheetMapper sheetMapper;
    private final SysSheetButtonMapper sheetButtonMapper;
    private final SysSheetFormAuthMapper sheetFormAuthMapper;
    private final SysSheetButtonAuthMapper buttonAuthMapper;
    private final SysSheetFormFieldAuthMapper fieldAuthMapper;

    /**
     * 获取应用按钮列表
     * @param roleId    角色ID
     * @return
     */
    @Override
    public SheetAuthTreeSelectVo getSheetButtonList(Long roleId) {

        SheetAuthTreeSelectVo treeSelectVo = new SheetAuthTreeSelectVo();
        List<SearchDataSourceDto> dtoList = new ArrayList<>();

        // 获取角色授予的应用按钮
        List<SysSheetButtonAuthVo> authVoList = sheetButtonAuthMapper.selectVoList(
            new LambdaQueryWrapper<SysSheetButtonAuth>().eq(SysSheetButtonAuth::getRoleId, roleId)
        );
        List<Long> ids = authVoList.stream().map(SysSheetButtonAuthVo::getSheetButtonId).toList();
        treeSelectVo.setCheckedKeys(ids);

        // 获取应用
        List<SysSheetVo> sheetList = sheetMapper.selectVoList(
            new LambdaQueryWrapper<SysSheet>().eq(SysSheet::getPid, 0).eq(SysSheet::getStatus, YesOrNoEnum.YES.getCode())
        );

        // 获取按钮
        List<SysSheetButtonVo> buttonList = sheetButtonMapper.selectVoList(
            new LambdaQueryWrapper<SysSheetButton>().eq(SysSheetButton::getStatus, YesOrNoEnum.YES.getCode())
        );
        sheetList.forEach(sheet -> {
            List<SysSheetButtonVo> filterList = buttonList.stream().filter(button -> button.getBindId().equals(sheet.getSheetId())).toList();
            SearchDataSourceDto dto = new SearchDataSourceDto();
            dto.setValue(sheet.getSheetId().toString());
            dto.setParentId(sheet.getSheetId().toString());
            dto.setLabel(sheet.getName());
            List<SearchDataSourceDto> childList = new ArrayList<>();
            if (filterList.size() > 0){
                for (SysSheetButtonVo button : filterList) {
                    SearchDataSourceDto child = new SearchDataSourceDto();
                    child.setValue(button.getSheetButtonId().toString());
                    child.setParentId(sheet.getSheetId().toString());
                    child.setLabel(button.getShowName());
                    childList.add(child);
                }
            }
            dto.setChildren(childList);
            dtoList.add(dto);
        });
        treeSelectVo.setDataSourceList(dtoList);

        return treeSelectVo;
    }

    /**
     * 保存应用按钮权限
     * @param buttonAuthBoList
     * @return
     */
    @Override
    public boolean saveSheetAuth(List<SysSheetButtonAuthBo> buttonAuthBoList) {
        // 删除原有数据
        sheetButtonAuthMapper.delete(
            new LambdaQueryWrapper<SysSheetButtonAuth>()
                .eq(SysSheetButtonAuth::getRoleId, buttonAuthBoList.get(0).getRoleId())
                .eq(SysSheetButtonAuth::getType, 2)
        );
        List<SysSheetButtonAuthBo> filterList = buttonAuthBoList.stream().filter(item -> !item.getSheetButtonId().equals(0L) && !item.getBindId().equals(0L)).toList();
        if (filterList.size() > 0){
            List<SysSheetButtonAuth> list = MapstructUtils.convert(filterList, SysSheetButtonAuth.class);
            return sheetButtonAuthMapper.insertBatch(list);
        } else {
            return true;
        }
    }

    /**
     * 保存应用表单授权
     *
     * @param authData
     * @return
     */
    @Override
    public boolean saveSheetFormAuthData(SheetFormAuthDataDto authData) {
        // 保存表单授权
        boolean saveFormAuth = saveSheetFormAuth(authData);
        // 保存字段授权
        boolean saveFormFieldAuth = saveSheetFormFieldAuth(authData);
        // 保存按钮授权
        boolean saveFormButtonAuth = saveSheetButtonAuth(authData);
        return saveFormAuth && saveFormFieldAuth && saveFormButtonAuth;
    }

    /**
     * 保存应用表单授权
     * @param authData
     * @return
     */
    public boolean saveSheetFormAuth(SheetFormAuthDataDto authData){
        boolean saveFlag = true;
        List<SysSheetFormAuthVo> sheetFormAuthList = authData.getSheetFormAuthList();
        // 删除原有数据
        sheetFormAuthMapper.delete(
            new LambdaQueryWrapper<SysSheetFormAuth>().eq(SysSheetFormAuth::getRoleId, authData.getRoleId())
        );
        if (!sheetFormAuthList.isEmpty()) {
            List<SysSheetFormAuth> list = MapstructUtils.convert(sheetFormAuthList, SysSheetFormAuth.class);
            saveFlag = sheetFormAuthMapper.insertBatch(list);

        }
        return saveFlag;
    }

    /**
     * 保存应用表单字段授权
     * @param authData
     * @return
     */
    public boolean saveSheetFormFieldAuth(SheetFormAuthDataDto authData){
        boolean saveFlag = true;
        boolean updateFlag = true;
        int delFlag = 1;
        List<SysSheetFormFieldAuthVo> sheetFieldList = authData.getSheetFieldAuthList();
        if (!sheetFieldList.isEmpty()) {
            // 新增
            List<SysSheetFormFieldAuthVo> saveList = sheetFieldList.stream().filter(item -> item.getHandleState().equals(HandleStateEnum.INSERT.getCode())).toList();
            if (!saveList.isEmpty()) {
                List<SysSheetFormFieldAuth> list = MapstructUtils.convert(saveList, SysSheetFormFieldAuth.class);
                saveFlag = fieldAuthMapper.insertBatch(list);
            }
            // 修改
            List<SysSheetFormFieldAuthVo> updateList = sheetFieldList.stream().filter(item -> item.getHandleState().equals(HandleStateEnum.UPDATE.getCode())).toList();
            if (!updateList.isEmpty()) {
                List<SysSheetFormFieldAuth> list = MapstructUtils.convert(updateList, SysSheetFormFieldAuth.class);
                updateFlag = fieldAuthMapper.updateBatchById(list);
            }
            // 删除
            List<SysSheetFormFieldAuthVo> delList = sheetFieldList.stream().filter(item -> item.getHandleState().equals(HandleStateEnum.DELETE.getCode())).toList();
            if (!delList.isEmpty()){
                delFlag = fieldAuthMapper.deleteBatchIds(delList.stream().map(SysSheetFormFieldAuthVo::getId).toList());
            }
        }
        return saveFlag && updateFlag && delFlag >0;
    }

    /**
     * 保存应用表单按钮授权
     * @param authData
     * @return
     */
    public boolean saveSheetButtonAuth(SheetFormAuthDataDto authData){
        boolean saveFlag = true;
        int delFlag = 1;
        List<SysSheetButtonAuthVo> sheetButtonAuthList = authData.getSheetButtonAuthList();
        if (!sheetButtonAuthList.isEmpty()) {
            // 新增
            List<SysSheetButtonAuthVo> saveList = sheetButtonAuthList.stream().filter(item -> item.getHandleState().equals(HandleStateEnum.INSERT.getCode())).toList();
            if (!saveList.isEmpty()) {
                List<SysSheetButtonAuth> list = MapstructUtils.convert(saveList, SysSheetButtonAuth.class);
                saveFlag = buttonAuthMapper.insertBatch(list);
            }
            // 删除
            List<SysSheetButtonAuthVo> delList = sheetButtonAuthList.stream().filter(item -> item.getHandleState().equals(HandleStateEnum.DELETE.getCode())).toList();
            if (!delList.isEmpty()){
                delFlag = buttonAuthMapper.deleteBatchIds(delList.stream().map(SysSheetButtonAuthVo::getId).toList());
            }
        }
        return saveFlag && delFlag > 0;
    }

    /**
     * 获取应用表单及按钮授权数据
     * @param roleId
     * @return
     */
    @Override
    public SheetFormAuthDataDto getSheetFormAuthData(Long roleId) {
        SheetFormAuthDataDto dataDto = new SheetFormAuthDataDto();
        dataDto.setRoleId(roleId);
        dataDto.setSheetFormAuthList(sheetFormAuthMapper.selectVoList(new LambdaQueryWrapper<SysSheetFormAuth>().eq(SysSheetFormAuth::getRoleId, roleId)));
        dataDto.setSheetFieldAuthList(fieldAuthMapper.selectVoList(new LambdaQueryWrapper<SysSheetFormFieldAuth>().eq(SysSheetFormFieldAuth::getRoleId, roleId)));
        dataDto.setSheetButtonAuthList(buttonAuthMapper.selectVoList(new LambdaQueryWrapper<SysSheetButtonAuth>().eq(SysSheetButtonAuth::getRoleId, roleId).eq(SysSheetButtonAuth::getType, 1)));
        return dataDto;
    }
}
